//
//  LCYHomeDetailController.m
//  EPA
//
//  Created by lanou3g on 16/4/20.
//  Copyright © 2016年 liu. All rights reserved.
//

#import "LCYHomeDetailController.h"
#import "LCYNetWorkRequestManager.h"
#import "LCYHomeListModel.h"
#import "LCYHomeListTableViewCell.h"
#import "URLHeaderDefine.h"
#import "LORefresh.h"
#import "LCYHomeContentViewController.h"
#import "LCYCollectionController.h"

@interface LCYHomeDetailController ()
/// 数据源数组
@property (nonatomic,strong) NSMutableArray *readDetailListArray;
/// 请求内容起始条数
@property (nonatomic,strong) NSString *start;
/// header 属性
@property (nonatomic,strong) LORefresh *headerRefresh;

@end
@implementation LCYHomeDetailController

- (void)dealloc {
    [self.tableView removeObserver:[self.tableView gifHeader] forKeyPath:@"contentOffset"];
    [self.tableView removeObserver:[self.tableView defaultFooter] forKeyPath:@"contentOffset"];
    [self.tableView removeObserver:[self.tableView defaultFooter] forKeyPath:@"contentSize"];
}
#pragma mark - 视图加载完成
- (void)viewDidLoad {
    [super viewDidLoad];
    
    /// 初始化数组
    self.readDetailListArray = [NSMutableArray array];
    
    // 解析数据
    self.start = @"0";
    [self loadDataFromServerType:self.type Start:self.start];
    
    // 注册
    [self.tableView registerNib:[UINib nibWithNibName:@"LCYHomeListTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"LCYHomeListTableViewCell"];
    
    // 上拉加载，下拉刷新
    [self addRefresh];
    
#pragma mark - 导航
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"收藏列表" style:(UIBarButtonItemStylePlain) target:self action:@selector(didClickCollectBtn:)];
    
    
    
}
- (void)didClickCollectBtn:(UIBarButtonItem *)sender {
    LCYCollectionController *collectionTVC = [[LCYCollectionController alloc]init];
    [self.navigationController pushViewController:collectionTVC animated:YES];
}

#pragma mark - 上拉加载，下拉刷新
- (void)addRefresh {
    // 添加下拉刷新
    __weak typeof(self)weakSelf = self;
    [self.tableView addRefreshWithRefreshViewType:LORefreshViewTypeHeaderGif refreshingBlock:^{
        // 移除
        [weakSelf.readDetailListArray removeAllObjects];
        [weakSelf.tableView reloadData];
        // 网络请求
        [weakSelf loadDataFromServerType:weakSelf.type Start:weakSelf.start];
    }];
    self.headerRefresh = [self.tableView gifHeader];
    [self.headerRefresh setGifName:@"demo"];
    
    
    /// 添加上提加载更多
    [self.tableView addRefreshWithRefreshViewType:LORefreshViewTypeFooterDefault refreshingBlock:^{
        NSInteger count = weakSelf.readDetailListArray.count;
        weakSelf.start = [NSString stringWithFormat:@"%ld",count];
        // 网络请求
        [weakSelf loadDataFromServerType:weakSelf.type Start:weakSelf.start];
    }];
}

#pragma mark - 网络请求，解析数据
- (void)loadDataFromServerType:(NSString *)type Start:(NSString *)start {
    [LCYNetWorkRequestManager requestURL:[NSURL URLWithString:READDETAILLIST_URL] RequestMethod:LCY_POST Params:@{@"deviceid":@"63A94D37-33F9-40FF-9EBB-481182338873",@"typeid":self.type,@"client":@"1",@"sort":@"addtime",@"limit":@10,@"version":@"3.0.2",@"auth":@"Wc06FCrkoq1DCMVzGMTikDJxQ8bm3Mrm2NpT9qWjwzcWP23tBKQx1c4P0",@"start":start} Result:^(NSData *data, NSURLResponse *response, NSError *error) {
//        NSLog(@"%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
        if (data) {
            NSMutableDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSDictionary *dataDic = jsonDic[@"data"];
            NSArray *listArray = dataDic[@"list"];
            for (NSDictionary *item in listArray) {
                LCYHomeListModel *model = [[LCYHomeListModel alloc]init];
                [model setValuesForKeysWithDictionary:item];
                [self.readDetailListArray addObject:model];
            }
            NSLog(@"%ld",self.readDetailListArray.count);
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.tableView reloadData];
                // 手动停止刷新、加载
                [[self.tableView gifHeader] endRefreshing];
                [[self.tableView defaultFooter]endRefreshing];
            });
            NSLog(@"%ld",self.readDetailListArray.count);
        }
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
#warning Incomplete implementation, return the number of sections
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete implementation, return the number of rows
    return self.readDetailListArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    LCYHomeListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LCYHomeListTableViewCell" forIndexPath:indexPath];
    cell.model = _readDetailListArray[indexPath.row];
    
    // Configure the cell...
    
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 150;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    LCYHomeContentViewController *contentVC = [[LCYHomeContentViewController alloc]init];
    LCYHomeListModel *model = self.readDetailListArray[indexPath.row];
    contentVC.homeListModel = model;
    [self.navigationController pushViewController:contentVC animated:YES];
    
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
